//
//  PPNearbyPeopleViewController.m
//  pet
//
//  Created by 陈无忌 on 11/14/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//
#define kSavedDeviceListKey @"pairedDeviceList"


#import "PPNearbyPeopleViewController.h"
#import "PPOtherUserCardViewController.h"
#import "PPUserCenterMainPageTableViewController.h"

#import "PPNearbyTableViewCell.h"

#import <CoreBluetooth/CoreBluetooth.h>
#import <CommonCrypto/CommonDigest.h>
#import <AKLocationManager/AKLocationManager.h>

#import "PPSystemConfiguraton.h"
#import "supportingHeadFiles.h"
#import "PPCustomBGTableView.h"

#import "PPBluetoothMonitor.h"
#import "PPUserAnnotation.h"

#import "PPSetMapAvatar.h"
//#import "PPFriendAnnotation.h"


@interface PPNearbyPeopleViewController ()<CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) PPSystemConfiguraton *config;
@property (nonatomic, strong) PPBluetoothMonitor *BLMonitor;
@property (strong, nonatomic) CLLocationManager *locationManager;
//
@property (strong, nonatomic) NSMutableArray *userArray;//附近用户列表
@property (strong, nonatomic) NSMutableArray *userLocationArray;//附近用户坐标集
@property (strong, nonatomic) NSMutableArray *nearByArray;//除自己以外的用户集合
@property (strong, nonatomic) NSMutableArray *allUserArray;//所有用户列表

@property (weak, nonatomic) IBOutlet UIButton *showMapButton;
@property (weak, nonatomic) IBOutlet UIButton *showListButton;
@property (weak, nonatomic) IBOutlet PPCustomBGTableView *nearbyTableView;

@end

@implementation PPNearbyPeopleViewController

- (PPBluetoothMonitor *)BLMonitor
{
    if (!_BLMonitor) {
        NSArray *pairedDevices = [[NSUserDefaults standardUserDefaults] objectForKey:kSavedDeviceListKey];
        _BLMonitor = [[PPBluetoothMonitor alloc] initWithIdentifiers:pairedDevices];
    }
    return _BLMonitor;
}

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (NSMutableArray *)userArray
{
    if (!_userArray) {
        _userArray = [NSMutableArray array];
    }
    return _userArray;
}

- (NSMutableArray *)userLocationArray
{
    if (!_userLocationArray) {
        _userLocationArray = [NSMutableArray array];
    }
    return _userLocationArray;
}

- (NSMutableArray *)nearByArray
{
    if (!_nearByArray) {
        _nearByArray = [NSMutableArray array];
    }
    return _nearByArray;
}

- (NSMutableArray *)allUserArray
{
    if (!_allUserArray) {
        _allUserArray = [NSMutableArray array];
    }
    return _allUserArray;
}

-(void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    _mapView.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _mapView.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
    [alert show];
}

- (void)showMap
{
    [self.showMapButton setSelected:YES];
    [self.showListButton setSelected:NO];
    [self.showMapButton setEnabled:NO];
    [self.showListButton setEnabled:YES];
    //table view hide
    [UIView animateWithDuration:0.35 animations:^(void){
        self.nearbyTableView.frame = CGRectMake(320, 44, self.view.frame.size.width, self.view.frame.size.height - 44);
    }completion:^(BOOL completed){
//        [self.IHFunTableView reloadData];
    }];
}

- (void)showList
{
    [self.showMapButton setSelected:NO];
    [self.showListButton setSelected:YES];
    [self.showListButton setEnabled:NO];
    [self.showMapButton setEnabled:YES];
    //table view show
    [UIView animateWithDuration:0.35 animations:^(void){
        self.nearbyTableView.frame = CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height - 44);
        //        self.groupView.frame = CGRectMake(0, 564, 100, 370);
    }completion:^(BOOL completed){
//        [self.nearbyTableView reloadData];
    }];
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.nearbyTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.nearbyTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.nearbyTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.nearbyTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //table view
    self.nearbyTableView.delegate = self;
    self.nearbyTableView.dataSource = self;
    self.nearbyTableView.frame = CGRectMake(320, 44, self.view.frame.size.width, self.view.frame.size.height - 44);
    //button
    [self.showMapButton addTarget:self action:@selector(showMap) forControlEvents:UIControlEventTouchUpInside];
    [self.showListButton addTarget:self action:@selector(showList) forControlEvents:UIControlEventTouchUpInside];
    [self showMap];
    //location
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [self.locationManager requestAlwaysAuthorization];
    }
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"Requesting when in use auth");
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.locationManager requestAlwaysAuthorization];
        }
    }else if (status == kCLAuthorizationStatusRestricted) {
        NSLog(@"Location services Restricted");
        [self alertShow:@"定位服务被限制！"];
        // Alert the user and send them to the settings to turn on location
    }else if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"Location services Denied");
        [self alertShow:@"定位服务被拒绝！"];
        // Alert the user and send them to the settings to turn on location
    }
    _mapView.showsUserLocation = YES;//显示定位图层
    _mapView.delegate = self;
    //set zoom
    for (int i = 0; i < 5; i++) {
        [_mapView zoomIn];
    }
    [self setLocation];
}

- (void)setLocation
{
    [HUD showUIBlockingIndicatorWithText:@"正在定位"];
    [AKLocationManager startLocatingWithUpdateBlock:^(CLLocation *location) {
        //get pos
        self.config.locationPosLatitude = location.coordinate.latitude;
        self.config.locationPosLongitude = location.coordinate.longitude;
        [self updateLocation];
    } failedBlock:^(NSError *error) {
        NSLog(@"fail");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [HUD hideUIBlockingIndicator];
        });
    }];
}

-(void)updateLocation
{
    NSString *url = [PPAPIList getAPIList].PPUpLoadUserLocation;
    NSDictionary *params = @{@"userId":@(self.config.userInfo.id),@"lng":@(self.config.locationPosLongitude),@"lat":@(self.config.locationPosLatitude),@"type":@2};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation,id responseObject){
        NSLog(@"other user location json is %@",responseObject);
        [self.userArray removeAllObjects];
        [self.userLocationArray removeAllObjects];
        [self.nearByArray removeAllObjects];
        [self.allUserArray removeAllObjects];
        NSDictionary *resultMap = responseObject[@"resultMap"];
        NSArray *list = resultMap[@"list"];
        NSArray *allUserDicList = resultMap[@"allUserList"];
        NSArray *allUser = [PPUserInfo arrayOfModelsFromDictionaries:allUserDicList];
        for (PPUserInfo *user in allUser) {
            if (user.id != self.config.userInfo.id) {
                [self.allUserArray addObject:user];
            }
        }

        
        if (list.count > 0) {
            NSError *err = nil;
            self.userArray = [PPUserInfo arrayOfModelsFromDictionaries:list error:&err];
                        for (PPUserInfo *user in self.userArray) {
                //把自己从用户列表中剔除
                if (user.id != self.config.userInfo.id) {
                    [self.nearByArray addObject:user];
//                    break ;
                }
                CLLocationCoordinate2D userLocation = CLLocationCoordinate2DMake(user.lat,  user.lng);
                NSDictionary *userCoordDict = BMKConvertBaiduCoorFrom(userLocation, BMK_COORDTYPE_GPS);
                userLocation = BMKCoorDictionaryDecode(userCoordDict);
                PPUserAnnotation *userL = [PPUserAnnotation annotationForPetShop:user];
                
                [_mapView addAnnotation:userL];
                if (userL.user.id == self.config.userInfo.id) {
                    [_mapView setCenterCoordinate:userL.coordinate animated:YES];
                }
                [self.userLocationArray addObject:userL];
            }
            [self.nearbyTableView reloadData];
        }
        [HUD hideUIBlockingIndicator];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"other user location json is %@",error);
        [HUD hideUIBlockingIndicator];
    }];
}

#pragma mark - Mapview Delegate
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    BMKPinAnnotationView *newAnnotationView = nil;
    if ([annotation isKindOfClass:[PPUserAnnotation class]]){
        PPUserAnnotation *PA = (PPUserAnnotation *)annotation;
        if (PA.user.id == self.config.userInfo.id) {
            newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
            newAnnotationView.image = [PPSetMapAvatar getMapSelfPoint];
//            [UIImage imageNamed:@"heartPin"];
            newAnnotationView.animatesDrop = NO;
            return newAnnotationView;
        }else{
            UIView *view = [[UIView alloc] init];
            
            UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
            [imageview setImageWithURL:[PPImageUrl getImageUrl:PA.user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultImage"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            imageview.layer.masksToBounds = YES;
            imageview.layer.cornerRadius = 8;
            
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 8, 100, 12)];
            nameLabel.font = [UIFont systemFontOfSize:12.0];
            nameLabel.textColor = [UIColor blackColor];
            nameLabel.text = PA.user.userName;
            nameLabel.numberOfLines = 1;
            [nameLabel sizeToFit];
            
            view.frame = CGRectMake(0, 0, 30 + nameLabel.frame.size.width + 5, 30);
            [view addSubview:imageview];
            [view addSubview:nameLabel];
            view.backgroundColor = [UIColor whiteColor];
            view.layer.masksToBounds = YES;
            view.layer.cornerRadius = 6;
            
            newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
            if (PA.user.gender == 0) {
                newAnnotationView.image = [UIImage imageNamed:@"malePoint"];
            }else{
                newAnnotationView.image = [UIImage imageNamed:@"femalePoint"];
            }
            newAnnotationView.animatesDrop = NO;
            newAnnotationView.paopaoView = [[BMKActionPaopaoView alloc] initWithCustomView:view];
            
            return newAnnotationView;
        }
    }
    return newAnnotationView;
}

//- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
//{
//}

- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view
{
    if ([view.annotation isKindOfClass:[PPUserAnnotation class]]) {
        PPUserAnnotation *userA = (PPUserAnnotation *)view.annotation;
        if (userA.user.id == self.config.userInfo.id) {
            PPUserCenterMainPageTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPUserCenterMainPageTableViewController"];
            [self.navigationController pushViewController:targetVC animated:YES];
            
        }else{
            PPOtherUserCardViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCardViewController"];
            targetVC.user = userA.user;
            [self.navigationController pushViewController:targetVC animated:YES];
        }
    }
}


#pragma mark - UITableView datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allUserArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PPNearbyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nearbyCell"];
    PPUserInfo *user = [self.allUserArray objectAtIndex:indexPath.row];
    [cell.nearbyAvatar setImageWithURL:[PPImageUrl getImageUrl:user.userAvatar] placeholderImage:[UIImage imageNamed:@"defaultAvatar"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    cell.nearbyNameLabel.text = user.userName;
    [cell.nearbyNameLabel sizeToFit];
    cell.gender.frame = CGRectMake(cell.nearbyNameLabel.frame.origin.x + cell.nearbyNameLabel.frame.size.width + 5, 16, 20, 20);
    if (user.gender == USER_MALE) {
        [cell.gender setImage:[UIImage imageNamed:@"male"]];
    }else{
        [cell.gender setImage:[UIImage imageNamed:@"female"]];
    }
    
    double distance = user.distance;
    if (distance < 1) {
        distance = distance * 1000;
        cell.distanceLabel.text = [NSString stringWithFormat:@"距您%.0f米",distance];
    }else{
        cell.distanceLabel.text = [NSString stringWithFormat:@"距您%.1f千米",distance];
    }
    if (user.signature) {
        cell.signature.text = user.signature;
    }else{
        cell.signature.text = @"主人很懒，什么都没写";
    }
    cell.signature.frame = CGRectMake(215, 20, 80, 15);
    cell.signature.numberOfLines = 2;
    [cell.signature sizeToFit];
    
    
    return cell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PPUserInfo *user = [self.allUserArray objectAtIndex:indexPath.row];
    PPOtherUserCardViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCardViewController"];
    targetVC.user = user;
    [self.navigationController pushViewController:targetVC animated:YES];
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - Custom IBAction
- (IBAction)reLocation:(id)sender {
    [_mapView removeAnnotations:self.userLocationArray];
    [self setLocation];
}

#pragma mark - Ibeacon
//过滤
- (NSArray *)filteredBeacons:(NSArray *)beacons
{
    // Filters duplicate beacons out; this may happen temporarily if the originating device changes its Bluetooth id
    NSMutableArray *mutableBeacons = [beacons mutableCopy];
    
    NSMutableSet *lookup = [[NSMutableSet alloc] init];
    for (int index = 0; index < [beacons count]; index++) {
        CLBeacon *curr = [beacons objectAtIndex:index];
        NSString *identifier = [NSString stringWithFormat:@"%@/%@", curr.major, curr.minor];
        
        // this is very fast constant time lookup in a hash table
        if ([lookup containsObject:identifier]) {
            [mutableBeacons removeObjectAtIndex:index];
        } else {
            [lookup addObject:identifier];
        }
    }
    
    return [mutableBeacons copy];
}

#pragma mark - bluetooth

- (IBAction)changeBeaconState:(UISwitch *)sender {
    //    [self.config setBeaconStaus:self.warningSwitch.on];
    //[self iBeaconSetting];
    if (sender.on) {
        [self.BLMonitor beginMonitoring];
    } else {
        [self.BLMonitor stopMonitoring];
    }
    
}

#pragma mark - Local notifications

- (void)sendLocalNotificationForBeaconRegion:(CLBeaconRegion *)region
{
    UILocalNotification *notification = [UILocalNotification new];
    
    // Notification details
    notification.alertBody = [NSString stringWithFormat:@"Entered beacon region for UUID: %@",
                              region.proximityUUID.UUIDString];   // Major and minor are not available at the monitoring stage
    notification.alertAction = NSLocalizedString(@"View Details", nil);
    notification.soundName = UILocalNotificationDefaultSoundName;
    
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}

- (void)sendLocalNotificationForOutOfDistance
{
    UILocalNotification *notification = [UILocalNotification new];
    
    // Notification details
    notification.alertBody = [NSString stringWithFormat:@"小萌宠已经走远啦，要注意哦～"];
    notification.alertAction = NSLocalizedString(@"View Details", nil);
    notification.soundName = UILocalNotificationDefaultSoundName;
    
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}



- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
    NSLog(@"Exited region: %@", region);
}

- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
    NSString *stateString = nil;
    switch (state) {
        case CLRegionStateInside:
            stateString = @"inside";
            break;
        case CLRegionStateOutside:
            stateString = @"outside";
            break;
        case CLRegionStateUnknown:
            stateString = @"unknown";
            break;
    }
    NSLog(@"State changed to %@ for region %@.", stateString, region);
//    self.distanceLabel.text = stateString ;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
